//表情
(function($){
	$.fn.facebox = function(options) {
		var defaults = {
			Event : "click", //响应事件		
			divid : "emotion-box", //表单ID（textarea外层ID）
			textid : "TextArea" //文本框ID
		};
		var options = $.extend(defaults,options);
		var $btn = $(this);//取得触发事件的ID
		
		//创建表情框
		var faceimg = '';
	    for(i=0;i<60;i++){  //通过循环创建60个表情，可扩展
			faceimg+='<li><a href="javascript:void(0)"><img src="../../images/emotion/'+(i+1)+'.gif" face="<emt>'+(i+1)+'</emt>"/></a></li>';
		};
		$("#"+options.divid).prepend("<div id='emotion-pic'><span class='Corner'></span><div class='Content'><h3><span>常用表情</span><a class='close' title='关闭'></a></h3><ul>"+faceimg+"</ul></div></div>");
	     $('#emotion-pic').css("display",'none');//创建完成后先将其隐藏
		//创建表情框结束
		
		var $facepic = $("#emotion-pic li img");
		//BTN触发事件，显示或隐藏表情层
		$btn.live(options.Event,function(e) {
			if($('#emotion-pic').is(":hidden")){
				$('#emotion-pic').show(360);
				$btn.addClass('in');
			}else{
				$('#emotion-pic').hide(360);
				$btn.removeClass('in');
			}
		});
		//插入表情
		$facepic.die().click(function(){
		     $('#emotion-pic').hide(360);
			 $("#"+options.textid).die().insertContent($(this).attr("face"));
			 console.log($(this).attr("face"));
			 $btn.removeClass('in');
		});			
		//关闭表情层
		$('#emotion-pic h3 a.close').click(function() {
			$('#emotion-pic').hide(360);
			$btn.removeClass('in');
		});	
		//当鼠标移开时，隐藏表情层，如果不需要，可注释掉
		//$('#emotion-pic').mouseleave(function(){
		//	$('#emotion-pic').hide(560);
		//	$btn.removeClass('in');
		//});	

  };  		
})(jQuery);
// 【漫画】 光标定位插件
$.fn.extend({  
	insertContent : function(myValue, t) {  
		var $t = $(this)[0];  
		if (document.selection) {  
			this.focus();  
			var sel = document.selection.createRange();  
			sel.text = myValue;  
			this.focus();  
			sel.moveStart('character', -l);  
			var wee = sel.text.length;  
			if (arguments.length == 2) {  
				var l = $t.value.length;  
				sel.moveEnd("character", wee + t);  
				t <= 0 ? sel.moveStart("character", wee - 2 * t	- myValue.length) : sel.moveStart("character", wee - t - myValue.length);  
				sel.select();  
			}  
		} else if ($t.selectionStart || $t.selectionStart == '0') {  
			var startPos = $t.selectionStart;  
			var endPos = $t.selectionEnd;  
			var scrollTop = $t.scrollTop;  
			$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos,$t.value.length);  
			this.focus();  
			$t.selectionStart = startPos + myValue.length;  
			$t.selectionEnd = startPos + myValue.length;  
			$t.scrollTop = scrollTop;  
			if (arguments.length == 2) { 
				$t.setSelectionRange(startPos - t,$t.selectionEnd + t);  
				this.focus(); 
			}  
		} else {                              
			this.value += myValue;                              
			this.focus();  
		}  
	}  
});
 
//表情解析
$.fn.extend({
	replaceface : function(faces){
		for(i=0;i<60;i++){
			faces=faces.replace('<emt>'+ (i+1) +'</emt>','<img src="images/face/'+(i+1)+'.gif">');
		}
		$(this).html(faces);
	}
});

(function($){
	$.fn.extend({
		goBack:function(){
			this.click(function(){
				history.go(-1);
				return false;
			});
		},
		textClean:function(){
			this.live("focus",function(){
				if($(this).val() == this.defaultValue){
					$(this).val("");
					$(this).removeClass("gray");
				};
			});
			this.live("blur",function(){
				if($.trim($(this).val()) == ""){
					$(this).val(this.defaultValue);
					$(this).addClass("gray");
				};
			});
			return this;
		},		
		setPosition:function(){
			if(this.height() < $(window).height()) {
				this.css({"top":($(window).height() - this.height())/2 + $(document).scrollTop()});
			}else{
				this.css({top:$(document).scrollTop()});
			}
			this.css({"left":($(window).width() - this.width())/2});
			return this;
		}		
	});
})(jQuery);

var wd = {
	init:function(){
		var that = this;
		that.shadeDiv = $("#shade-div");
		that.header = $("#header");
		that.content = $("#content");
		that.footer = $("#footer");
        that.navHd = $(".nav-hd");
		that.tabNavLi = $(".tab-nav li");
		that.tabContent = $(".tab-content");
		that.pullUp = $("#pull-up");
		that.checkAll = $("#checkAll");
		that.inputItem = $(".inputitem");
		that.areaCheckAll = $("#areaCheckAll");
		that.areaCheck = $(".area-check");
        that.titField = $("#title-field");
		that.authorField = $("#author-field");
		that.imgField = $("#img-field");
		that.contentField = $("#content-field");
		that.appMsgs = new Array();
		that.appMsgs["appmsgItem1"] = {title:"",author:"",img:"",content:""};
		that.appMsgs["appmsgItem2"] = {title:"",author:"",img:"",content:""};

        that.loadingOut;
        that.bindEvent();
	},
	bindEvent:function(){
		var that = this;
		$(".closePopBtn,.cancelBtn").live("click",function(){
			$(".popbox").hide();
			$("#shade-div").hide();
		});	
		$(".close_error_pop").live("click",function(){
             $("#error_pop").remove();
             $("#photo_pop").remove();
             $("#shade-div-error").remove();
             if($.isFunction(wd.error_fn_back)){
                 wd.error_fn_back();
                 delete wd.error_fn_back;
             }
             return false;
        });

        //侧边导航
        that.navHd.click(function(){
            var $parent = $(this).parent();
            var subList = $parent.find(".sub-list");
            if(subList.is(":hidden")){
                $(this).addClass("arrow-down").removeClass("arrow-up");
                $parent.siblings().find(".sub-list").hide();
                $parent.siblings().find(".nav-hd").removeClass("arrow-down").addClass("arrow-up");
                subList.show();
                
                subList.find("li").siblings().removeClass("cur");
                subList.find("li:first").addClass("cur");
                
                $(".nav_tab_menu").html(subList.html());
                $("#mainframe").attr("src",$(this).attr("url"));
            }else{
               /* $(this).removeClass("arrow-down").addClass("arrow-up");
                subList.hide();*/
            }
        });
        $(".sub-list li").click(function(){
            var $parent = $(this).closest(".parent-menu");
            $(this).addClass("cur").siblings().removeClass("cur");
            $parent.siblings().find("li").removeClass("cur");
            
            var subList = $(this).closest(".sub-list");
            $(".nav_tab_menu").html(subList.html());
            $("#mainframe").attr("src",$(this).attr("url"));
        });
        
        $(".nav_tab_menu li").live("click",function(){
        	var $parent = $(this).closest(".nav_tab_menu");
            $(this).addClass("cur").siblings().removeClass("cur");
            $parent.siblings().find("li").removeClass("cur");
            
            var subList = $("#nav").find(".sub-list");
            if(subList.not(":hidden")){
            	subList.html($(".nav_tab_menu").html());
            	$("#mainframe").attr("src",$(this).attr("url"));
            }
        });
			
		$(".key-words").textClean();
		
		that.tabNavLi.live("click",function(){
			$(this).addClass("selected").siblings().removeClass("selected");
			var index = that.tabNavLi.index(this);
			that.tabContent.eq(index).show().siblings().hide();
		});

        $("#select-img-btn").click(function(){
            $("#select-img").show().setPosition();
            that.shadeDiv.show();
        });
        $("#select-audio-btn").click(function(){
            $("#select-audio").show().setPosition();
            that.shadeDiv.show();
        });
        $("#select-appmsg-btn").click(function(){
            $("#select-appmsg").show().setPosition();
            that.shadeDiv.show();
        });
		$("#upload-appmsg").live("click",function(){
			$("#build-appmsg").show().setPosition();
            that.shadeDiv.show();
			fillForm($(".js-appmsg-item").attr("id"));  // 跳到到第一个
		});

        $("#resource-btn").click(function(){
            $("#resource-pop").show().setPosition();
            that.shadeDiv.show();
        });

        //表情点击事件
        $("#js_switch").facebox({
            Event : "click",	//触发事件
            divid : "emotion-box", //外层DIV ID
            textid : "js_editArea" //文本框 ID
        });
		//音频播放
		$("#media_list .item").each(function(i){
			$("#jp_jplayer_" + i).jPlayer({
				ready: function () {
					$(this).jPlayer("setMedia", {
						mp3:"Love is.mp3"
					});
				},
				swfPath: "js",
				supplied: "mp3",
				wmode: "window",
				smoothPlayBar: true,
				keyEnabled: true,
				cssSelectorAncestor: "#jp_container_" + i
			});	
		});		
		//多图选择
		$(".appmsg-list li").live("click",function(){
			$(this).find(".appmsg-mask")
				.show()
				.closest("li")
				.siblings()
				.find(".appmsg-mask").hide();		
			$(this).find(".icon-appmsg-selected")
				.show()
				.closest("li")
				.siblings()
				.find(".icon-appmsg-selected").hide();
		});
		//新建多图文消息
		$("#js_appmsgAddBtn").click(function(){
			var html = '<div class="appmsg-add-item js-appmsg-item"> \
				<img src="" class="appmsg-thumb hide" /> \
				<span class="appmsg-thumb default">缩略图</span> \
				<h3 class="appmsg-title original">标题</h3> \
				<div class="appmsg-edit-mask"> \
					<a href="javascript:;" class="edit-appmsg" title="编辑"></a> \
					<a href="javascript:;" class="del-appmsg" title="删除"></a> \
				</div> \
			</div>';
			if($(".appmsg-add-item").size() < 9){
				// 全局保存数据
				var id = "appmsgItem" + guid();
				wd.appMsgs[id] = {title:"",author:"",img:"",content:""};
				
				// 添加页面元素
				var el = $(html).attr("id",id);
				$(".appmsg-editing").append(el);
				
				// 与编辑框关联
				$(".appmsg-editor").attr("relateId",id);
				fillForm(id);
				
				// 监听编辑事件
				el.find(".edit-appmsg").click(function(){
					edit($(this));
				});

				// 监听删除事件
				el.find(".del-appmsg").click(function(){
					del($(this));
				});				
			}else{
				clearTimeout(that.loadingOut);
				that.pullUp.show().animate({"opacity":1},500);
			}
            that.loadingOut = setTimeout(function(){
                that.pullUp.animate({
                    'opacity': 0
                }, 500);
            },3000);
		});
		
		function guid() {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
				return v.toString(16);
			});
		}
		
		$(".js-appmsg-item").find(".edit-appmsg").click(function(){
			edit($(this));
		});

		$(".js-appmsg-item").find(".del-appmsg").click(function(){
			del($(this));
		});		
		
		function edit(item){
			var id = item.closest(".js-appmsg-item").attr("id");
			fillForm(id);
		}
				
		function del(item){
			var box = item.closest(".js-appmsg-item");
			var id = box.attr("id");
			box.remove();
			delete wd.appMsgs[id];   // 删除数据
			fillForm($(".js-appmsg-item").attr("id"));  // 跳回到第一个
		}
		
		function fillForm(id){
			var d = wd.appMsgs[id];
			that.titField.val(d.title);
			that.authorField.val(d.author);
			that.imgField.val(d.img);
			that.contentField.val(d.content);
			$(".appmsg-editor").attr("relateId",id);
		}
		
        that.titField.change(function(){
			var id = $(".appmsg-editor").attr("relateId");
            var txt = $(this).val();
            $("#"+id).find(".appmsg-title").html(txt);
			wd.appMsgs[id].title = txt;
        });
		that.authorField.change(function(){
			var id = $(".appmsg-editor").attr("relateId");
            var txt = $(this).val();
			wd.appMsgs[id].author = txt;		
		});
		that.imgField.change(function(){
			var id = $(".appmsg-editor").attr("relateId");
            var txt = $(this).val();
			wd.appMsgs[id].img = txt;
		});
		that.contentField.change(function(){
			var id = $(".appmsg-editor").attr("relateId");
            var txt = $(this).val();
			wd.appMsgs[id].content = txt;			
		});
		
		//全选
		that.checkAll.click(function(){
			that.inputItem.attr("checked",this.checked);
		});
		that.inputItem.click(function(){
			that.checkAll.attr("checked",that.inputItem.length == that.inputItem.filter(":checked").length);
		});
		
		that.wordCount();	
	},
	getMinHeight:function(){
		var that = this;
		var minHeight = $(window).height() - that.header.outerHeight() - that.footer.outerHeight();
		that.content.css({'min-height':minHeight});
	},
	error_pop:function(title,message,fn){
		wd.error_fn_back = fn || function(){};
        var error_pop_html = $('<div class="popbox" id="error_pop"><div class="popbox-hd" id="error_title"><h2>' + title + '</h2><a class="closePopBtn close_error_pop" href="#" title="关闭"></a></div><div class="popbox-bd error-tips"><p id="message"><i></i>' + message +'</p><p class="pop-btns"><a href="javasrcipt:;" class="btn blue-btn">确定</a></p></div></div>');
        $("body").append(error_pop_html)
        var error_mask = $('<div class="shade-div" id="shade-div-error"></div>');
        var timer = setInterval(function(){
            if($("#error_pop").length > 0) {
                $("#error_pop").show().setPosition();
                $("body").append(error_mask);
                clearInterval(timer);
            }
        },100)

    },
	wordCount:function(options){
		var opt = {
			divName:"emotion-box", //外层容器的class
			textareaName:"edit-area", //textarea的class
			numName:"num", //数字的class
			num:600 //数字的最大数目
		};
		var options = $.extend(opt, options);

		//定义变量
		var $onthis;//指向当前
		var $divname=options.divName; //外层容器的class
		var $textareaName=options.textareaName; //textarea的class
		var $numName=options.numName; //数字的class
		var $num=options.num; //数字的最大数目

		function isChinese(str){  //判断是不是中文
			var reCh=/[\x00-\xff]/g;
			return !reCh.test(str);
		}
		function numChange(){
			var strlen=0; //初始定义长度为0
			var txtval = $onthis.val();
			for(var i=0;i<txtval.length;i++){
				if(isChinese(txtval.charAt(i))==true){
					strlen=strlen+2;//中文为2个字符
				}else{
					strlen=strlen+1;//英文一个字符
				}
			}
			strlen=Math.ceil(strlen/2);//中英文相加除2取整数
			if($num-strlen<0){
				$par.html("超出 <b style='color:red;font-weight:lighter' class="+$numName+">"+Math.abs($num-strlen)+"</b> 字"); //超出的样式
			}
			else{
				$par.html("您还可以输入 <b class="+$numName+">"+($num-strlen)+"</b> 字"); //正常时候
			}
			$b.html($num-strlen);
		}
		$("."+$textareaName).live("focus",function(){
			$b=$(this).parents("."+$divname).find("."+$numName); //获取当前的数字
			$par=$b.parent();
			$onthis=$(this); //获取当前的textarea
			var setNum=setInterval(numChange,500);
		});
	}

}

$(function(){
	wd.init();
});
